import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../index.dart';
import 'dart:math';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart' as map;
import 'package:amap_location_fluttify/amap_location_fluttify.dart' as location;
import 'dart:io';
import '../../common/file_utils.dart';

class WorkOrderAddPage extends StatefulWidget {
  late Order? order;

  WorkOrderAddPage({Key? key, this.order}) : super(key: key);

  @override
  _WorkOrderAddState createState() => _WorkOrderAddState();
}

class _WorkOrderAddState extends State<WorkOrderAddPage> {
  late Order order;
  List<OrderCfg>? repairSource;
  List<OrderCfg>? emergencyLevel;
  late List<TyPhoto> selectPhotos;
  List<Dept>? deptList;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    selectPhotos = [];
    if (widget.order != null) {
      //编辑
      order = Order.fromJson(widget.order!.toJson());
      if (order.annexUrl != null) {
        for (String url in order.annexUrl!.split(",")) {
          if (url.isNotEmpty) {
            selectPhotos.add(TyPhoto(url: url));
          }
        }
      }
    } else {
      //新建
      order = Order();
    }
    repairSource = OrderCfgCache().getOrderCfg(2);
    emergencyLevel = OrderCfgCache().getOrderCfg(3);
    deptList = DeptCache().getCurrentDeptList();
  }

  @override
  Widget build(BuildContext context) {
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
          appBar: AppBar(
            title: Text(
              widget.order == null ? "新增工单" : "编辑工单",
            ),
            centerTitle: true,
          ),
          body: _buildBody(), // 构建主页面
        ),
      ),
    );
  }

  Widget _buildBody() {
    return Padding(
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      child: ListView(
        children: <Widget>[
          CommonTextField(
            title: "客户名称",
            content: order.customerName,
            maxLength: 10,
            onChanged: (value) {
              order.customerName = value;
            },
          ),
          CommonTextField(
            title: "联系电话",
            content: order.customerPhone,
            keyboardType: TextInputType.phone,
            maxLength: 15,
            onChanged: (value) {
              order.customerPhone = value;
            },
          ),
          CommonSelect(
            title: "报修来源",
            isRequired: true,
            content: order.repairResourceName,
            onTap: () {
              List<String>? list =
                  OrderCfgCache.orderCfgListToStringList(repairSource);

              if (list != null) {
                int index =
                    max(0, list.indexOf(order.repairResourceName ?? ""));
                PickerUtil.showModalPicker(context,
                    adapter: PickerDataAdapter<String>(pickerdata: list),
                    selecteds: [index], onConfirm: (Picker picker, List value) {
                  Debug.info("返回的value$value");
                  int index = value.first;
                  setState(() {
                    OrderCfg orderCfg = repairSource![index];
                    order.repairResource = orderCfg.id;
                    order.repairResourceName = orderCfg.cfgTypeName;
                  });
                });
              } else {
                showToast("暂无数据");
              }
            },
          ),
          CommonSelect(
            title: "故障地点",
            isRequired: true,
            content: order.defectAddress,
            onTap: () async {
              FocusScope.of(context).unfocus();
              List? result = await Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => MapSelectPage()));
              if (result != null && result.length == 2) {
                map.ReGeocode reGeocode = result[0];
                location.LatLng coordinate = result[1];
                order.latitude = "${coordinate.latitude}";
                order.longitude = "${coordinate.longitude}";
                setState(() {
                  order.defectAddress = reGeocode.formatAddress as String?;
                });
              }
            },
          ),
          CommonTextField(
            title: "详细地址",
            content: order.address,
            maxLength: 40,
            onChanged: (value) {
              order.address = value;
            },
          ),
          CommonSelect(
            title: "指派处理部门",
            content: DeptCache().getDeptName(order.handleDeptId),
            isRequired: true,
            onTap: () {
              List<String>? list = DeptCache.deptListToStringList(deptList);

              if (list != null) {
                int index =
                    max(0, list.indexOf(order.repairResourceName ?? ""));
                PickerUtil.showModalPicker(context,
                    adapter: PickerDataAdapter<String>(pickerdata: list),
                    selecteds: [index], onConfirm: (Picker picker, List value) {
                  setState(() {
                    order.handleDeptId = deptList![picker.selecteds[0]].id;
                  });
                });
              } else {
                showToast("暂无数据");
              }
            },
          ),
          CommonSelect(
            title: "工单紧急程度",
            isRequired: true,
            content: order.orderUrgencyName,
            onTap: () {
              List<String>? list =
                  OrderCfgCache.orderCfgListToStringList(emergencyLevel);

              if (list != null) {
                int index = max(0, list.indexOf(order.orderUrgencyName ?? ""));
                PickerUtil.showModalPicker(context,
                    adapter: PickerDataAdapter<String>(pickerdata: list),
                    selecteds: [index], onConfirm: (Picker picker, List value) {
                  setState(() {
                    order.orderUrgencyName =
                        emergencyLevel![picker.selecteds[0]].cfgTypeName;
                    order.orderType = emergencyLevel![picker.selecteds[0]].id;
                    order.handleTime = int.parse(
                        emergencyLevel![picker.selecteds[0]].cfgValue ?? "0");
                  });
                });
              } else {
                showToast("暂无数据");
              }
            },
          ),
          CommonMultiLineTextField(
            title: "报修内容",
            isRequired: true,
            isHideDivide: true,
            maxLength: 100,
            content: order.suppleMemo,
            onChanged: (value) {
              order.suppleMemo = value;
            },
          ),
          CommonPhotoSelect(
            title: "附图",
            photos: selectPhotos,
            max: 12,
            // selectPhoto: (List<TyPhoto> photos) {
            //   setState(() {
            //     // selectPhotos = photos;
            //   });
            // },
            isHideDivide: true,
          ),
          CommonMultiLineTextField(
            title: "备注",
            isHideDivide: true,
            maxLength: 100,
            content: order.orderMemo,
            onChanged: (value) {
              order.orderMemo = value;
            },
          ),
          Container(
            margin:
                const EdgeInsets.only(top: 30, bottom: 30, left: 16, right: 16),
            child: Row(
              children: [
                Expanded(
                  child: CommonButton.outlinedButton(context,
                      text: "保存", onPressed: _formValidation),
                ),
                const SizedBox(
                  width: 20,
                ),
                Expanded(
                  child: CommonButton.elevatedButton(context, text: "保存并发送",
                      onPressed: () {
                    _formValidation(isSend: true);
                  }),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _formValidation({bool isSend = false}) async {
    if (order.repairResourceName == null) {
      showToast("请选择报修来源");
      return;
    }
    if (order.defectAddress == null ||
        order.latitude == null ||
        order.longitude == null) {
      showToast("请选择故障地点");
      return;
    }
    if (order.handleDeptId == null) {
      showToast("请选择处理部门");
      return;
    }
    if (order.orderUrgencyName == null) {
      showToast("请选择工单紧急程度");
      return;
    }
    if (order.suppleMemo == null) {
      showToast("请选择报修内容");
      return;
    }
    showLoading(context);
    // 如果有图片就上传图片
    _onUploadPhoto(isSend);
  }

  void _onUploadPhoto(bool isSend) async {
    List files = [];
    for (TyPhoto photo in selectPhotos) {
      if (photo.url == null && photo.file != null) {
        File? file = await photo.file!.file;
        if (file != null) {
          files.add(MultipartFileExtended.fromFileSync(
              await FileUtils.compressImage(file),
              filename: file.path.substring(file.path.lastIndexOf("/") + 1)));
        }
      }
    }
    if (files.isNotEmpty) {
      try {
        ResponseData<List<TyFile>> responseData =
            await Api(context).uploadFile(data: {"files": files});
        int i = 0;
        if (responseData.success) {
          String annexUrl = "";
          for (TyPhoto photo in selectPhotos) {
            if (photo.url == null && photo.file != null) {
              photo.url = responseData.dataModel?[i].link;
              i++;
            }
            if (annexUrl.isEmpty) {
              annexUrl = photo.url!;
            } else {
              annexUrl = "$annexUrl,${photo.url}";
            }
          }
          order.annexUrl = annexUrl;
          _onSave(isSend);
        } else {
          Navigator.of(context).pop();
          showToast("上传图片失败");
        }
      } on DioError catch (e) {
        Navigator.of(context).pop();
        showToast(e.message);
      } on Error catch (e) {
        Navigator.of(context).pop();
        showToast("图片上传失败");
      }
    } else {
      _onSave(isSend);
    }
  }

  void _onSave(bool isSend) async {
    if (widget.order != null) {
      //编辑
      try {
        ResponseData responseData =
            await Api(context).editOrder(data: order.toJson());
        if (responseData.success) {
          if (isSend) {
            //发送工单
            ResponseData responseData =
                await Api(context).sendOrder(orderId: order.id ?? "");
            if (!responseData.success) {
              Navigator.of(context).pop();
              showToast(responseData.msg);
              return;
            }
          }
          eventBus.fire(OrderEvent(EventType.edit, order));
          Navigator.of(context).pop();
          Navigator.popUntil(context, ModalRoute.withName("WorkOrderDetails"));
          await showToast("操作成功");

          //跳转到详情
          // Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => WorkOrderDetailsPage(orderId: order.id!)), (route) => route == null);
          Navigator.of(context).pushReplacement(MaterialPageRoute(
              settings: const RouteSettings(name: "WorkOrderDetails"),
              builder: (context) => WorkOrderDetailsPage(orderId: order.id!)));
        } else {
          Navigator.of(context).pop();
          showToast(responseData.msg);
        }
      } on Error {
        Navigator.of(context).pop();
        showToast(S.of(context).networkError);
      }
    } else {
      //新增
      Order? mOrder;
      try {
        ResponseData<Order> responseData =
            await Api(context).addOrder(data:  order.toJson());
        if (responseData.success) {
          mOrder = responseData.dataModel;
          if (isSend) {
            //发送工单
            ResponseData responseData =
                await Api(context).sendOrder(orderId: mOrder?.id ?? "");
            if (!responseData.success) {
              Navigator.of(context).pop();
              showToast(responseData.msg);
              return;
            }
          }
          Navigator.of(context).pop();
          if (mOrder != null && mOrder.id != null) {
            eventBus.fire(OrderEvent(EventType.add, mOrder));
            await showToast("操作成功");
            //跳转到详情
            Navigator.of(context).pushReplacement(MaterialPageRoute(
                settings: const RouteSettings(name: "WorkOrderDetails"),
                builder: (context) =>
                    WorkOrderDetailsPage(orderId: mOrder?.id ?? "")));
          }
        } else {
          Navigator.of(context).pop();
          showToast(responseData.msg);
        }
      } on Error {
        Navigator.of(context).pop();
        showToast(S.of(context).networkError);
      }
    }
  }
}
